<template>
  <!-- 搜索表单 -->
  <div class="max-w-7xl mx-auto mt-18 mb-4">
    <form class="relative group" @submit.prevent="handleSearch">
      <label for="default-search" class="mb-2 text-sm font-medium text-gray-900 sr-only dark:text-white">搜索</label>

      <!-- 主搜索区域 -->
      <div class="relative overflow-hidden shadow-lg transition-all duration-300 bg-white dark:bg-gray-800 border-0 group-hover:shadow-xl">
        <!-- 搜索图标 -->
        <div class="absolute top-4 start-0 flex items-center ps-7 pointer-events-none">
          <svg class="w-6 h-6 text-[#991E29] dark:text-[#e57373] opacity-70 group-hover:opacity-100 transition-opacity duration-300" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
            <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z"/>
          </svg>
        </div>

        <!-- 搜索输入框 -->
        <div class="relative">
          <input
            type="search"
            id="default-search"
            v-model="searchKeyword"
            class="block w-full p-4 ps-16 pr-32 text-lg text-gray-900 border-0 bg-transparent focus:ring-0 focus:outline-none dark:text-white"
            placeholder="搜索内容..."
            required
          />

          <!-- 搜索按钮 -->
          <button
            type="submit"
            class="text-white absolute right-3 top-1/2 transform -translate-y-1/2 bg-[#991E29] hover:bg-[#C32A31] focus:outline-none font-medium text-base px-6 py-2 transition-all rounded-full duration-300 hover:scale-105 flex items-center justify-center"
          >
            搜索
          </button>
        </div>

        <!-- 筛选区域 -->
        <div class="px-7 pb-4 border-t border-gray-100 dark:border-gray-700 mt-2">
          <div class="flex flex-wrap gap-4 items-center">
            <span class="text-sm text-gray-600 dark:text-gray-400 font-medium">高级筛选:</span>

            <!-- 分类筛选 -->
            <div class="flex items-center gap-2">
              <label for="category-select" class="text-sm text-gray-600 dark:text-gray-400">分类:</label>
              <select
                id="category-select"
                v-model="selectedCategory"
                class="text-sm border border-gray-300 rounded-md px-3 py-1 bg-white dark:bg-gray-700 dark:border-gray-600 dark:text-white focus:ring-2 focus:ring-[#991E29] focus:border-transparent transition-all duration-200"
              >
                <option value="">全部分类</option>
                <option v-for="category in categories" :key="category" :value="category">
                  {{ category }}
                </option>
              </select>
            </div>

            <!-- 学院筛选 -->
            <div class="flex items-center gap-2">
              <label for="section-select" class="text-sm text-gray-600 dark:text-gray-400">学院:</label>
              <select
                id="section-select"
                v-model="selectedSection"
                class="text-sm border border-gray-300 rounded-md px-3 py-1 bg-white dark:bg-gray-700 dark:border-gray-600 dark:text-white focus:ring-2 focus:ring-[#991E29] focus:border-transparent transition-all duration-200"
              >
                <option value="">全部学院</option>
                <option v-for="section in sections" :key="section" :value="section">
                  {{ section }}
                </option>
              </select>
            </div>

            <!-- 重置筛选按钮 -->
            <button
              v-if="selectedCategory || selectedSection"
              type="button"
              @click="resetFilters"
              class="text-sm text-[#991E29] hover:text-[#C32A31] font-medium transition-colors duration-200 flex items-center gap-1"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
              </svg>
              重置筛选
            </button>
          </div>
        </div>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { articleApi } from '../../../utils/api';

const router = useRouter();
const route = useRoute();

// 定义emit
const emit = defineEmits(['api-error']);

// 搜索关键词和筛选条件
const searchKeyword = ref('');
const selectedCategory = ref('');
const selectedSection = ref('');

// 分类和学院选项
const categories = ref([]);
const sections = ref([]);
const loading = ref(false);

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = '';
};

// 重置筛选条件
const resetFilters = () => {
  selectedCategory.value = '';
  selectedSection.value = '';
};

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim() && !selectedCategory.value && !selectedSection.value) {
    return;
  }

  // 构建查询参数
  const query = {};

  if (searchKeyword.value.trim()) {
    query.keyword = searchKeyword.value.trim();
  }

  if (selectedCategory.value) {
    query.category = selectedCategory.value;
  }

  if (selectedSection.value) {
    query.section = selectedSection.value;
  }

  // 跳转到搜索结果页面
  router.push({
    path: '/search',
    query
  });
};

// 监听筛选条件变化，自动触发搜索
watch([selectedCategory, selectedSection], () => {
  // 如果有筛选条件变化且有关键词或其他筛选条件，自动搜索
  if (selectedCategory.value || selectedSection.value || searchKeyword.value.trim()) {
    handleSearch();
  }
});

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await articleApi.getAllCategories();
    console.log('分类API响应:', response);

    // 由于axios响应拦截器返回response.data，所以response就是实际的数据
    if (Array.isArray(response)) {
      // 如果response直接是数组
      categories.value = response;
      console.log('设置分类数据(直接数组):', response);
    } else if (response && response.data && Array.isArray(response.data)) {
      // 如果response是对象且包含data字段
      categories.value = response.data;
      console.log('设置分类数据(嵌套):', response.data);
    } else if (response) {
      // 其他情况，尝试直接使用
      console.log('未知响应格式:', response);
      categories.value = [];
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
    emit('api-error', '获取分类列表失败');
  }
};

// 获取学院列表
const fetchSections = async () => {
  try {
    const response = await articleApi.getAllSections();
    console.log('学院API响应:', response);

    // 由于axios响应拦截器返回response.data，所以response就是实际的数据
    if (Array.isArray(response)) {
      // 如果response直接是数组
      sections.value = response;
      console.log('设置学院数据(直接数组):', response);
    } else if (response && response.data && Array.isArray(response.data)) {
      // 如果response是对象且包含data字段
      sections.value = response.data;
      console.log('设置学院数据(嵌套):', response.data);
    } else if (response) {
      // 其他情况，尝试直接使用
      console.log('未知响应格式:', response);
      sections.value = [];
    }
  } catch (error) {
    console.error('获取学院列表失败:', error);
    emit('api-error', '获取学院列表失败');
  }
};

// 初始化数据
const initializeData = () => {
  // 从URL参数中恢复搜索条件
  if (route.query.keyword) {
    searchKeyword.value = route.query.keyword;
  }
  if (route.query.category) {
    selectedCategory.value = route.query.category;
  }
  if (route.query.section) {
    selectedSection.value = route.query.section;
  }
};

// 页面加载时初始化
onMounted(async () => {
  loading.value = true;
  try {
    // 并行获取分类和学院列表
    await Promise.all([
      fetchCategories(),
      fetchSections()
    ]);

    // 初始化搜索条件
    initializeData();
  } catch (error) {
    console.error('初始化数据失败:', error);
  } finally {
    loading.value = false;
  }
});

// 监听路由变化，更新搜索条件
watch(() => route.query, (newQuery) => {
  if (route.path === '/search' || route.path === '/') {
    searchKeyword.value = newQuery.keyword || '';
    selectedCategory.value = newQuery.category || '';
    selectedSection.value = newQuery.section || '';
  }
}, { deep: true });
</script>

<style scoped>
/* 响应式设计样式 */
@media (max-width: 768px) {
  /* 移动端样式调整 */
  .max-w-7xl {
    padding: 0 1rem;
  }

  /* 搜索输入框在移动端的调整 */
  .block.w-full.p-4 {
    padding: 0.75rem 1rem 0.75rem 3rem;
    font-size: 1rem;
  }

  /* 搜索按钮在移动端的调整 */
  .absolute.right-3 {
    right: 0.5rem;
    padding: 0.5rem 1rem;
    font-size: 0.875rem;
  }

  /* 清除按钮在移动端的调整 */
  .absolute.right-24 {
    right: 5rem;
  }

  /* 筛选区域在移动端的调整 */
  .flex.flex-wrap.gap-4 {
    flex-direction: column;
    gap: 0.75rem;
    align-items: flex-start;
  }

  /* 筛选项在移动端的调整 */
  .flex.items-center.gap-2 {
    width: 100%;
    justify-content: space-between;
  }

  /* 下拉选择框在移动端的调整 */
  select {
    flex: 1;
    max-width: 60%;
  }
}

@media (max-width: 480px) {
  /* 超小屏幕样式调整 */
  .text-lg {
    font-size: 1rem;
  }

  .px-7 {
    padding-left: 1rem;
    padding-right: 1rem;
  }

  /* 搜索图标位置调整 */
  .absolute.top-4.start-0 {
    top: 0.75rem;
    left: 0.5rem;
  }

  /* 输入框左边距调整 */
  .ps-16 {
    padding-left: 2.5rem;
  }

  /* 清除按钮位置调整 */
  .absolute.right-24 {
    right: 4rem;
  }

  /* 搜索按钮位置调整 */
  .absolute.right-3 {
    right: 0.25rem;
    padding: 0.375rem 0.75rem;
    font-size: 0.75rem;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  select {
    background-color: #374151;
    border-color: #4B5563;
    color: white;
  }

  select:focus {
    outline: 2px solid #991E29;
    border-color: transparent;
  }
}

/* 筛选区域动画效果 */
.border-t {
  transition: all 0.3s ease;
}

/* 选择框聚焦效果 */
select:focus {
  transform: scale(1.02);
  transition: all 0.2s ease;
}

/* 重置按钮悬停效果 */
button:hover svg {
  transform: rotate(180deg);
  transition: transform 0.3s ease;
}
</style>
